package cn.jhz.learn.community_dynamic.manager;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.jhz.learn.community_dynamic.dao.PostJpaRepository;
import cn.jhz.learn.community_dynamic.model.PostEntity;

@Service
public class PostManager {
    private final PostJpaRepository postJpaRepository;

    @Autowired
    public PostManager(PostJpaRepository postJpaRepository) {
	super();
	this.postJpaRepository = postJpaRepository;
    }
    
//    public Long countByTopicId(Integer topicId) {
//	Specification<PostEntity> specification = new Specification<PostEntity>() {
//	    /**
//	     * 
//	     */
//	    private static final long serialVersionUID = -7786291064559271193L;
//
//	    @Override
//	    public Predicate toPredicate(Root<PostEntity> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
//		List<Predicate> predicates = new ArrayList<>();
//		//根据roleId 查询 user
//		Join<TopicEntity, PostEntity> join = root.join("topics", JoinType.LEFT);
//		predicates.add(criteriaBuilder.equal(join.get("id"), topicId));
//		
//		return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
//	    }
//	};
//	return this.postJpaRepository.count(specification);
//    }

//    public Long countTodayByTopicId(Integer topicId) {
//	Specification<PostEntity> specification = new Specification<PostEntity>() {
//	    /**
//	     * 
//	     */
//	    private static final long serialVersionUID = -3288399862508482728L;
//
//	    @Override
//	    public Predicate toPredicate(Root<PostEntity> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
//		List<Predicate> predicates = new ArrayList<>();
//		//根据roleId 查询 user
//		Join<TopicEntity, PostEntity> join = root.join("topics", JoinType.LEFT);
//		predicates.add(criteriaBuilder.equal(join.get("id"), topicId));
//		predicates.add(criteriaBuilder.equal(root.get("createTime"), criteriaBuilder.currentDate()));
//		
//		return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
//	    }
//	};
//	return this.postJpaRepository.count(specification);
//    }
    
    @Transactional
    public PostEntity updateInstanceColumn(PostEntity entity, Byte status) {
	entity.setStatus(status);
	return entity;
    }
    
    @Transactional
    public void deleteInstance(PostEntity entity) {
	this.postJpaRepository.delete(entity);
	this.postJpaRepository.flush();
    }
    
    @Transactional
    public PostEntity addInstance(PostEntity entity) {
	return this.postJpaRepository.save(entity);
    }
}
